#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <string.h>
#include <sys/types.h>			/* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

#define FDS_LENGTH 1024

int main(int argc, char * * argv)
{
	int sockfd = socket(AF_INET, SOCK_STREAM, 0);
	if(-1 == sockfd)
	{
		perror("socket:");
		exit(-1);
	}
	struct sockaddr_in server_addr;
	memset(&server_addr, 0, sizeof(server_addr));

	server_addr.sin_family = AF_INET;
	server_addr.sin_port = htons(4396);
	server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

	int ret = bind(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr));
	if(-1 == ret)
	{
		perror("bind:");
		exit(-1);
	}

	if(-1 == listen(sockfd, 10))
	{
		perror("listen:");
		close(sockfd);
		exit(-1);
	}

	struct pollfd fds[FDS_LENGTH] = {0};
	fds[sockfd].fd = sockfd;
	fds[sockfd].events = POLLIN;
	int maxfd = sockfd;

	while(1)
	{
		int nready = poll(fds, maxfd + 1, -1);
		if(fds[sockfd].revents & POLLIN)
		{
			struct sockaddr_in client_addr;
			socklen_t len = sizeof(client_addr);
			int clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &len);
			if(-1 == clientfd)
			{
				perror("accept:");
				close(sockfd);
				exit(-1);
			}
			fds[clientfd].fd = clientfd;
			fds[clientfd].events = POLLIN;
			maxfd = clientfd;
		}
		int i = 0;
		char buffer[128] = {0};
		ssize_t count;
		for(i = sockfd + 1; i <= maxfd; i ++)
		{
			if(fds[i].revents & POLLIN)
			{
				count = recv(i, buffer, sizeof(buffer), 0);
				if(0 == count)
				{
					printf("disconnected\n");
					fds[i].fd = -1;
					fds[i].events = -1;
					close(i);
					continue;
				}
				printf("clientfd: %d, count: %ld, buffer: %s\n", i, count, buffer);
				send(i, buffer, count, 0);
			}
		}
	}
	close(sockfd);
	exit(0);
}




